package com.sany.taskmanager.ui.activity;

import static com.sany.taskmanager.global.Key.IntentKey.ACTIVITY_INDEX;
import static com.sany.taskmanager.global.Key.IntentKey.MATERIAL_NUM;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.sany.taskmanager.R;
import com.sany.taskmanager.bean.ColorBean;
import com.sany.taskmanager.databinding.ActivityMainBinding;
import com.sany.taskmanager.global.Constants;
import com.sany.taskmanager.http.IHttpCallBack;
import com.sany.taskmanager.manager.DataManager;
import com.sany.taskmanager.room.entity.LocalTaskInfo;
import com.sany.taskmanager.ui.fragment.CarModelFragment;
import com.sany.taskmanager.ui.fragment.MaterialFragment;
import com.sany.taskmanager.util.ExcelUtil;
import com.sany.taskmanager.util.FileUtil;
import com.sany.taskmanager.util.LogUtil;
import com.sany.taskmanager.util.ScanGunKeyEventHelper;
import com.sany.taskmanager.util.ToastUtil;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 信息录入页面
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> implements View.OnClickListener, ScanGunKeyEventHelper.OnScanSuccessListener {

    private final SparseArray<Fragment> mFragmentMap = new SparseArray<>(2);
    private Fragment mCurrentFragment;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    private ActivityResultLauncher<Intent> scanResult;
    private ScanGunKeyEventHelper mScanGunKeyEventHelper;

    @Override
    protected void initData() {
        mScanGunKeyEventHelper = new ScanGunKeyEventHelper(this);
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            //此处是跳转的result回调方法
            if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                Uri uri = result.getData().getData();
                String filePath = FileUtil.getFileAbsolutePath(MainActivity.this, uri);
                LogUtil.d("filePath = " + filePath);
                // 读取选择的excel文件
                readExcel(filePath);

            }
        });
        scanResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            //此处是跳转的result回调方法
            if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                String materialNum = result.getData().getStringExtra(MATERIAL_NUM);
                if (TextUtils.isEmpty(materialNum)) {
                    return;
                }

                if (mCurrentFragment == null) {
                    return;
                }
                if (mCurrentFragment instanceof MaterialFragment) {
                    ((MaterialFragment) mCurrentFragment).refreshMaterialNum(materialNum);
                } else if (mCurrentFragment instanceof CarModelFragment) {
                    ((CarModelFragment) mCurrentFragment).refreshCarModelNum(materialNum);
                }

            }
        });

        vBinding.llCarModel.setOnClickListener(this);
        vBinding.llMaterial.setOnClickListener(this);

        mFragmentMap.put(R.id.ll_car_model, CarModelFragment.newInstance());
        mFragmentMap.put(R.id.ll_material, MaterialFragment.newInstance());

        switchFragment(R.id.ll_car_model);

        initColorInfo();

    }

    private void switchFragment(int checkedId) {
        if (checkedId == R.id.ll_car_model) {
            vBinding.tvCarModel.setTextColor(ContextCompat.getColor(this, R.color.color_4CB5FF));
            vBinding.viewCarModel.setVisibility(View.VISIBLE);
            vBinding.tvMaterial.setTextColor(ContextCompat.getColor(this, R.color.white));
            vBinding.viewMaterial.setVisibility(View.INVISIBLE);
        } else if (checkedId == R.id.ll_material) {
            vBinding.tvCarModel.setTextColor(ContextCompat.getColor(this, R.color.white));
            vBinding.viewCarModel.setVisibility(View.INVISIBLE);
            vBinding.tvMaterial.setTextColor(ContextCompat.getColor(this, R.color.color_4CB5FF));
            vBinding.viewMaterial.setVisibility(View.VISIBLE);
        }

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment nextFragment = mFragmentMap.get(checkedId);
        if (mCurrentFragment == null) {
            ft.add(R.id.fl_container, mCurrentFragment = nextFragment);
        } else {
            if (nextFragment.isAdded()) {
                ft.hide(mCurrentFragment);
                ft.show(mCurrentFragment = nextFragment);
            } else {
                ft.hide(mCurrentFragment);
                ft.add(R.id.fl_container, mCurrentFragment = nextFragment);
            }
        }
        ft.commitNowAllowingStateLoss();
    }

    /**
     * 读取excel数据
     */
    private void readExcel(String filePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Observable.create((ObservableOnSubscribe<List<LocalTaskInfo>>) emitter -> {
                List<LocalTaskInfo> taskList = ExcelUtil.readExcel(MainActivity.this, getResources().getStringArray(R.array.excel_cells), filePath);
                emitter.onNext(taskList);
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<LocalTaskInfo>>() {
                @Override
                public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                }

                @Override
                public void onNext(@io.reactivex.rxjava3.annotations.NonNull List<LocalTaskInfo> taskList) {
                    if (taskList == null) {
                        ToastUtil.showToast(MainActivity.this, getString(R.string.tip_excel_empty_or_error));
                        return;
                    }
                    // 校验颜色是否合法
                    StringBuilder sBuilder = new StringBuilder();
                    for (LocalTaskInfo info : taskList) {
                        if (info.getColorType() == -1) {
                            sBuilder.append(",").append(info.getColorName());
                        }
                    }
                    if (sBuilder.length() > 0) {
                        ToastUtil.showToast(MainActivity.this, String.format(getString(R.string.format_excel_boom_color_error), sBuilder.substring(1)));
                        return;
                    }
                    // 更新数据列表
                    if (mCurrentFragment == null) {
                        return;
                    }
                    if (mCurrentFragment instanceof MaterialFragment) {
                        ((MaterialFragment) mCurrentFragment).refreshList(taskList);
                    } else if (mCurrentFragment instanceof CarModelFragment) {
                        ((CarModelFragment) mCurrentFragment).refreshList(taskList);
                    }
                }

                @Override
                public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                    ToastUtil.showToast(MainActivity.this, e.getMessage());
                }

                @Override
                public void onComplete() {

                }
            });
        }
    }


    private void initColorInfo() {
        showLoading();
        compositeDisposable.add(taskViewModel.getColorList(new IHttpCallBack<List<ColorBean>>() {
            @Override
            public void onSuccess(List<ColorBean> colorList) {
                hideLoading();
                if (colorList == null || colorList.isEmpty()) {
                    ToastUtil.showToast(MainActivity.this, getString(R.string.tip_get_color_failed));
                    return;
                }
                DataManager.getInstance().setColorList(colorList);
            }

            @Override
            public void onFailed(String message) {
                hideLoading();
                ToastUtil.showToast(MainActivity.this, message);
            }
        }));
    }

    @Override
    public void onClick(View v) {
        switchFragment(v.getId());
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                goDocuments();
            } else {
                ToastUtil.showToast(this, getString(R.string.tip_authority_select));
            }
        } else if (requestCode == 2) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                ToastUtil.showToast(this, getString(R.string.tip_open_ble_connect_permission));
            } else {
                checkScanGun();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkBleConnect();
    }

    // 校验蓝牙权限
    private void checkBleConnect() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
        } else {
            checkScanGun();
        }
    }

    /**
     * 校验是否链接了扫码枪
     */
    private void checkScanGun() {
        if (!mScanGunKeyEventHelper.hasScanGun()) {
            LogUtil.d(getString(R.string.tip_no_scan_gun), MainActivity.class);
//            ToastUtil.showToast(this, getString(R.string.tip_no_scan_gun));

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mScanGunKeyEventHelper.onDestroy();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mScanGunKeyEventHelper.isScanGunEvent(event)) {
            mScanGunKeyEventHelper.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onScanSuccess(String barcode) {
        LogUtil.d("barcode = " + barcode);
        if (mCurrentFragment == null) {
            return;
        }
        if (mCurrentFragment instanceof MaterialFragment) {
            ((MaterialFragment) mCurrentFragment).onScanSuccess(barcode);
        } else if (mCurrentFragment instanceof CarModelFragment) {
            ((CarModelFragment) mCurrentFragment).onScanSuccess(barcode);
        }
    }


    /**
     * 跳转到文件管理器
     */
    public void goDocuments() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");// 设置文件类型，这里设置为任意类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);// 表示可以打开的文件
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);// 只显示本地文件
        intentActivityResultLauncher.launch(intent);
    }

    public void skip2Scan() {
        scanResult.launch(new Intent(this, ScanActivity.class).putExtra(ACTIVITY_INDEX, Constants.ScanIndex.ACTIVITY_MAIN));
    }

    /**
     * 校验读写权限
     */
    public void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) { // android11 需要手动授权：Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
                if (Environment.isExternalStorageManager()) {
                    goDocuments();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivity(intent);
                }
            } else {
                goDocuments();
            }
        }
    }
}